<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\ModelTree;
use Encore\Admin\Traits\AdminBuilder;

class StopReason extends Model
{
    use ModelTree, AdminBuilder;

    protected $table = 'hawk_stopreason';

    public $timestamps = false;

    const TYPE_NOT_IN_PLAN = 1;
    const TYPE_OUTSIDE = 2;
    const TYPE_IN_PLAN = 3;
    const TYPE_INSIDE = 4;

    public static $typeTexts = [
        self::TYPE_INSIDE => '内部原因',
        self::TYPE_OUTSIDE => '外部原因',
        self::TYPE_IN_PLAN => '计划停机',
        self::TYPE_NOT_IN_PLAN => '非计划停机',
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'description', 'productlineId', 'parentId', 'type', 'sort',
    ];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setTitleColumn('name');
        $this->setParentColumn('parentId');
        $this->setOrderColumn('sort');
    }

    public function getTypeTextAttribute()
    {
        return self::$typeTexts[$this->type] ?? '';
    }

    public function walkThroughRoot(StopReason $stopReason)
    {
        $allNodes = $this->allNodes();
        $current = $stopReason->toArray();
        $out = [$current];
        while ($parent = $this->getParent($current[$this->parentColumn], $allNodes)) {
            $out[] = $parent;
            $current = $parent;
        }
        return $out;
    }

    private function getParent($parentId = 0, $allNodes)
    {
        foreach ($allNodes as $node) {
            if ($node['id'] == $parentId) {
                return $node;
            }
        }
    }

    public function faultDescriptions()
    {
        return $this->hasMany(FaultDesc::class, 'stopreasonId');
    }



}
